package com.xj.qq;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.xj.qq.adapters.MsgAdapters;
import com.xj.qq.domain.Msg;

import java.util.ArrayList;
import java.util.List;

public class Chatting extends AppCompatActivity {

    private List<Msg> msgList = new ArrayList<> (  );
    private EditText mEt;
    private Button send;
    private Button back;
    private RecyclerView mRv;
    private MsgAdapters adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.chatting);
        initMsg();//初始化消息数据

        mEt = (EditText) findViewById (R.id.mEt);
        send = (Button) findViewById (R.id.send);
        back = (Button) findViewById(R.id.goback);
        mRv = (RecyclerView) findViewById (R.id.mRv);

        //建立数据和RecyclerView之间的联系
        LinearLayoutManager layoutManager = new LinearLayoutManager ( this);
        mRv.setLayoutManager ( layoutManager );//制定RecyclerView的布局方式
        adapter = new MsgAdapters( msgList );//将数据传递到MsgAdapter构造函数中
        mRv.setAdapter ( adapter );

        send.setOnClickListener ( new View.OnClickListener () {
            @Override
            public void onClick(View view) {
                String content = mEt.getText ().toString ();
                if(!"".equals ( content )){//如果输入框不为空，就执行以下内容
                    Msg msg = new Msg ( content,Msg.TYPE_SENT );
                    msgList.add ( msg );
                    adapter.notifyItemInserted (msgList.size ()-1);
                    mRv.scrollToPosition ( msgList.size ()-1 );//将显示的数据定位到 最后一行
                    mEt.setText ( "" );//点击发送后清空输入框的内容
                }
            }
        } );
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Chatting.this, MainActivity.class);
                startActivity(intent);
            }
        });
    }
    private void initMsg(){
        Msg msg1 = new Msg ( "天门中断楚江开",Msg.TYPE_RECEIVED );
        msgList.add ( msg1 );//将msg1加入到列表msgList中
        Msg msg2 = new Msg ( "碧水东流至此回",Msg.TYPE_SENT );
        msgList.add ( msg2 );
        Msg msg3 = new Msg ( "两岸青山相对出",Msg.TYPE_RECEIVED );
        msgList.add ( msg3 );
    }
}
